//
//  PublicChatBar.m
//  BaiTengIM
//
//  Created by awh on 2019/6/26.
//  Copyright © 2019年 awh. All rights reserved.
//

#import "PublicChatBar.h"

#import "BTChatBarToolView.h"
#import "BTStickerKeyboardView.h"

#import "AudioRecordHelper.h"
#import "StickerModel.h"

#import "StickerDataManager.h"
#import "NSAttributedString+PPAddition.h"

#define ktextViewMinHeight 44
#define ktextViewMaxHeight 120
#define kATFormat  @"@%@ "
#define kATRegular @"@[\\u4e00-\\u9fa5\\w\\-\\_]+ "


@interface PublicChatBar ()<UITextViewDelegate, BTChatBarToolViewDelegate, AudioRecordHelperDelegate, BTStickerKeyboardDelegate>

@property (nonatomic) CGFloat version;
@property (nonatomic) CGFloat previousTextViewContentHeight;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) BTChatBarToolView *toolView;
@property(nonatomic, strong) BTStickerKeyboardView *stickerView;
@property (nonatomic, strong) UIView *currentMoreView;

@property(nonatomic, strong) UIButton *voiceRecordBtn;

@property (nonatomic, strong) UIButton *voiceBtn;
@property (nonatomic, strong) UIButton *faceBtn;
@property (nonatomic, strong) UIButton *moreBtn;
@property (nonatomic, strong) UIButton *mentBtn;
@property (nonatomic, strong) UIButton *selectedButton;
@property (nonatomic, strong) NSArray<UIButton *> *buttonArray;

//@property (nonatomic, strong) UIButton *forbidBtn;




@end

@implementation PublicChatBar

- (void)clearMoreViewAndSelectedButton {
    if (self.currentMoreView) {
        [self.currentMoreView removeFromSuperview];
        self.currentMoreView = nil;
        [self remakeTopViewConstraints];
    }
    if (self.selectedButton) {
        self.selectedButton.selected = NO;
        self.selectedButton = nil;
    }
}

- (void)clearInputViewText {
    self.textView.text = @"";
    [self updateTextViewHeight];
}


- (instancetype)init {
    self = [super init];
    if (self) {
        _version = [[[UIDevice currentDevice] systemVersion] floatValue];
        _previousTextViewContentHeight = ktextViewMinHeight;
        [self _setupSubviews];
    }
    
    return self;
}

#pragma mark - Subviews

- (void)_setupSubviews {
    self.backgroundColor = [UIColor whiteColor];
    
//    self.topView = [[UIView alloc] init];
    [self addSubview:self.menuView];
    [self.menuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.height.equalTo(@40);
        make.right.equalTo(self.mas_right);
        make.bottom.equalTo(self).offset(-EMVIEWBOTTOMMARGIN);
    }];
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = kColor_Gray;
    [self.menuView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.menuView);
        make.left.equalTo(self.menuView);
        make.right.equalTo(self.menuView);
        make.height.equalTo(@1);
    }];
//    UIView *line = [[UIView alloc] init];
//    line.backgroundColor = kColor_Gray;
//    [self.menuView addSubview:line];
//    [line mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.topView);
//        make.left.equalTo(self.topView);
//        make.right.equalTo(self.topView);
//        make.height.equalTo(@1);
//    }];
//    [self.topView addSubview:self.mentBtn];
//    [self.topView addSubview:self.voiceBtn];
//    [self.topView addSubview:self.textView];
//    [self.topView addSubview:self.voiceRecordBtn];
//    [self.topView addSubview:self.faceBtn];
//    [self.topView addSubview:self.moreBtn];
//    _buttonArray = @[self.mentBtn,self.voiceBtn, self.faceBtn, self.moreBtn];
//    [self.mentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.height.equalTo(@30);
//        make.bottom.equalTo(self.topView).offset(-10);
//        make.left.equalTo(self.topView).offset(10);
//    }];
//    [self.voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.height.equalTo(@30);
//        make.bottom.equalTo(self.topView).offset(-10);
//        make.left.equalTo(self.mentBtn.mas_right).offset(10);
//    }];
//    [self.moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(30, 30));
//        make.bottom.equalTo(self.voiceBtn);
//        make.right.equalTo(self.topView.mas_right).offset(-10);
//    }];
//    [self.faceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.equalTo(self.voiceBtn);
//        make.height.equalTo(self.voiceBtn);
//        make.bottom.equalTo(self.voiceBtn);
//        make.right.equalTo(self.moreBtn.mas_left).offset(-10);
//    }];
//    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.topView).offset(5);
//        make.left.equalTo(self.voiceBtn.mas_right).offset(5);
//        make.right.equalTo(self.faceBtn.mas_left).offset(-5);
//        make.height.mas_equalTo(ktextViewMinHeight);
//    }];
//    [self.voiceRecordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.bottom.right.equalTo(self.textView);
//    }];
//
//    [self addSubview:self.topView];
//    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.equalTo(self);
//        make.bottom.equalTo(self.textView.mas_bottom).offset(5);
//        make.bottom.equalTo(self).offset(-EMVIEWBOTTOMMARGIN);
//    }];
//    [self.topView addSubview:self.menuView];
//    [self.menuView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.mentBtn.mas_right);
//        make.height.equalTo(self.topView);
//        make.right.equalTo(self.topView.mas_right);
//    }];


}


#pragma mark - Private

- (CGFloat)getTextViewContontHeight
{
    if (self.version >= 7.0) {
        return ceilf([self.textView sizeThatFits:self.textView.frame.size].height);
    } else {
        return self.textView.contentSize.height;
    }
}

- (void)updateTextViewHeight
{
    
    CGFloat height = [self getTextViewContontHeight];
//    CGFloat w = self.textView.width;
//    BTIMLog(@"输入框宽度：%.2f, 高度：%.2f", w, height);
    if (height < ktextViewMinHeight) {
        height = ktextViewMinHeight;
    }
    if (height > ktextViewMaxHeight) {
        height = ktextViewMaxHeight;
    }
    
    if (height == self.previousTextViewContentHeight) {
        return;
    }
    self.previousTextViewContentHeight = height;
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
    [self.topView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height + 10);
    }];
}

- (void)remakeTopViewConstraints {
    if (self.currentMoreView) {
        [self.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.equalTo(@(self.previousTextViewContentHeight + 10));
            make.bottom.equalTo(self.textView.mas_bottom).offset(5);
            make.bottom.equalTo(self.currentMoreView.mas_top);
        }];
    } else {
        [self.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.bottom.equalTo(self.textView.mas_bottom).offset(5);
            make.bottom.equalTo(self).offset(-EMVIEWBOTTOMMARGIN);
        }];
    }
}

#pragma mark - 按钮事件
- (void)buttonAction:(UIButton *)aButton {
    [self.textView resignFirstResponder];
    
    aButton.selected = !aButton.selected;
    if (self.currentMoreView) {
        [self.currentMoreView removeFromSuperview];
        self.currentMoreView = nil;
        [self remakeTopViewConstraints];
    }
    
    if (self.selectedButton != aButton) {
        self.selectedButton.selected = NO;
        self.selectedButton = nil;
        self.selectedButton = aButton;
    } else {
        self.selectedButton = nil;
    }
    
    if (aButton.selected) {
        self.selectedButton = aButton;
    }
}
- (void)moreBtnAction:(UIButton *)sender {
    [self buttonAction:sender];
    if (sender.selected) {
        self.currentMoreView = self.toolView;
        [self addSubview:self.toolView];
        [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self);
            make.right.equalTo(self);
            make.height.equalTo(@200); // 84
            make.bottom.equalTo(self).offset(-EMVIEWBOTTOMMARGIN);
        }];
        [self remakeTopViewConstraints];
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarDidShowMoreViewAction)]) {
            [self.delegate chatBarDidShowMoreViewAction];
        }
    }
}

- (void)faceBtnAction:(UIButton *)sender {
    [self buttonAction:sender];
    if (sender.selected) {
        self.voiceRecordBtn.hidden = YES;
        self.currentMoreView = self.stickerView;
        [self addSubview:self.stickerView];
        [self.stickerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self);
            make.right.equalTo(self);
            make.height.equalTo(@200);
            make.bottom.equalTo(self).offset(-EMVIEWBOTTOMMARGIN);
        }];
        [self remakeTopViewConstraints];
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarDidShowMoreViewAction)]) {
            [self.delegate chatBarDidShowMoreViewAction];
        }
    }

}

- (void)voiceBtnAction:(UIButton *)sender {
    [self buttonAction:sender];
    self.voiceRecordBtn.hidden = !sender.isSelected;
}

//- (void)forbidBtnction:(UIButton *)sender {
//    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarForbidBtnDidClickAction)]) {
//        [self.delegate chatBarForbidBtnDidClickAction];
//    }
//}

- (void)mentBtnAction:(UIButton *)sender{
    
    if (sender.tag >=1000) {

        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarChangeMenu:)]) {
           [self.delegate chatBarChangeMenu:sender];
            
        }
    }else{
        sender.selected = !sender.selected;
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarChangeMenu:)]) {
               [self.delegate chatBarChangeMenu:sender];
               if (sender.selected) {
                   self.menuView.hidden = NO;
               }else{
                   self.menuView.hidden = YES;
               }
             }
    }
   
}

- (NSString *)getAudioOrVideoPath {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    path = [path stringByAppendingPathComponent:@"BaiTengIMRecord"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}

#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if (self.currentMoreView) {
        [self.currentMoreView removeFromSuperview];
        [self.topView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self).offset(-EMVIEWBOTTOMMARGIN);
        }];
    }
    
    for (UIButton *button in self.buttonArray) {
        if (button.isSelected) {
            button.selected = NO;
            break;
        }
    }
    
    return YES;
}
-(void)selectedUserWith:(NSMutableDictionary*)userDic Type:(NSInteger)type
{
    if (type==1) {
        _userDic =userDic;
        _array111=[_userDic allKeys];
        _idArray=[NSMutableArray arrayWithArray:_array111];
    }else
    {
        [_userDic removeAllObjects];
        [_idArray removeAllObjects];
    }

    AAIMLog(@"选中的用户 - --  %@---类型%ld",userDic,type);
}
-(void)sendSuccessClearUserdata
{
    [_userDic removeAllObjects];
    [_idArray removeAllObjects];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([text isEqualToString:@""])
    {
        NSRange selectRange = textView.selectedRange;
        if (selectRange.length > 0)
        {
            //用户长按选择文本时不处理
            return YES;
        }
        
        // 判断删除的是一个@中间的字符就整体删除
        NSMutableString *string = [NSMutableString stringWithString:textView.text];
        NSArray *matches = [self findAllAt];
        
        BOOL inAt = NO;
        NSInteger index = range.location;
        for (NSTextCheckingResult *match in matches)
        {
            NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
            if (NSLocationInRange(range.location, newRange))
            {
                inAt = YES;
                index = match.range.location;
                NSString *string1 = [string substringWithRange:match.range];//截取范围内的字符串
                NSString *string22 = [string1  substringFromIndex: 1];//截取范围内的字符串substringToIndex
                NSString *string3333 = [string22 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                for (int i=0; i<_idArray.count; i++) {
                    NSString * name=_idArray[i];
                    NSString * aaa=[NSString stringWithFormat:@"%@",[_userDic objectForKey:name]];
                    if ([aaa isEqualToString:string3333]) {
                        [_idArray removeObject:name];
                        [_userDic removeObjectForKey:name];
                    }
                }
                [string replaceCharactersInRange:match.range withString:@""];
                break;
            }
        }
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(inputView:shouldChangeTextInRange:replacementText:userIdsArray:)]) {
            [self.delegate inputView:self.textView shouldChangeTextInRange:range replacementText:text userIdsArray:_idArray];
        }
        
        if (inAt)
        {
            textView.text = string;
            textView.selectedRange = NSMakeRange(index, 0);
            return NO;
        }
    }
    
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(inputView:shouldChangeTextInRange:replacementText:userIdsArray:)]) {
        return [self.delegate inputView:self.textView shouldChangeTextInRange:range replacementText:text userIdsArray:_idArray];
    }
    
    return YES;
    
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(inputView:shouldChangeTextInRange:replacementText:userIdsArray:)]) {
        [self.delegate inputView:self.textView shouldChangeTextInRange:NSMakeRange(0, 0) replacementText:@"" userIdsArray:_idArray];
    }
}

#pragma mark - BTStickerKeyboardDelegate

- (void)stickerKeyboard:(BTStickerKeyboardView *)stickerKeyboard didClickAtSticker:(StickerModel *)sticker {
    if (!sticker) return;
    
    UIImage *emojiImage = [UIImage imageNamed:sticker.image];
    if (!emojiImage) return;
    NSRange selectedRange = self.textView.selectedRange;
    NSString *emojiString = [NSString stringWithFormat:@"[%@]", sticker.desc];
    NSMutableAttributedString *emojiAttributedString = [[NSMutableAttributedString alloc] initWithString:emojiString];
    [emojiAttributedString pp_setTextBackedString:[PPTextBackedString stringWithString:emojiString] range:emojiAttributedString.pp_rangeOfAll];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    [attributedText replaceCharactersInRange:selectedRange withAttributedString:emojiAttributedString];
    self.textView.attributedText = attributedText;
    self.textView.selectedRange = NSMakeRange(selectedRange.location + emojiAttributedString.length, 0);
    
    [self updateTextViewHeight];
}

- (void)stickerKeyboardDidClickDeleteButton:(BTStickerKeyboardView *)stickerKeyboard {
    
    NSArray<PPStickerMatchingResult *> *matches = [[StickerDataManager sharedInstance] matchingEmojiForString:self.textView.text];
    for (PPStickerMatchingResult *match in matches)
    {
        NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
        if (NSLocationInRange(self.textView.text.length - 1, newRange)) {
            NSMutableString *string = [NSMutableString stringWithString:self.textView.text];
            [string replaceCharactersInRange:match.range withString:@""];
            self.textView.text = string;
            break;
        }
    }
    
    [self updateTextViewHeight];
}

- (void)stickerKeyboardDidClickSendButton:(BTStickerKeyboardView *)stickerKeyboard {
    [self textView:self.textView shouldChangeTextInRange:NSMakeRange(self.textView.text.length - 1, 1) replacementText:@"\n"];
}

#pragma mark - Private

- (NSArray<NSTextCheckingResult *> *)findAllAt
{
    // 找到文本中所有的@
    NSString *string = self.textView.text;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kATRegular options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
    return matches;
}

- (void)textViewDidChange:(UITextView *)textView {
    [self updateTextViewHeight];
    AAIMLog(@"=========");
}

- (void)markAtBlue:(NSString *)text {
    NSString *sendString = text;
    [self.textView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15.0] range:NSMakeRange(0, sendString.length)];
    [self.textView.textStorage addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, sendString.length)];
    
    NSError *error = nil;
    NSRegularExpression *atPersionRE = [NSRegularExpression regularExpressionWithPattern:@"@[\u4e00-\u9fa5a-zA-Z0-9_-]+" options:NSRegularExpressionCaseInsensitive error:&error];
    [atPersionRE enumerateMatchesInString:text options:NSMatchingReportProgress range:NSMakeRange(0, text.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        if (result.range.location != NSNotFound) {
            [self.textView.textStorage removeAttribute:NSForegroundColorAttributeName range:result.range];
        
            [self.textView.textStorage addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:60/255.0 green:150/255.0 blue:255/255.0 alpha:1/1.0] range:result.range];
        }
    }];
}
#pragma mark - BTChatBarToolViewDelegate

- (void)toolView:(BTChatBarToolView *)toolView didSelectedAtItem:(NSInteger)item {
    switch (item) {
        case 0:
            [self photoBtnDidClickAction];
            break;
        case 1:
            [self cameraBtnDidClickAction];
            break;
        case 2:
            [self sendBusinessCardAction];
            break;

            
        default:
            break;
    }
}
//- (NSArray *)getTopicRangeArray:(NSAttributedString *)attributedString {
//    NSAttributedString *traveAStr = attributedString ?: _textView.attributedText;
//    __block NSMutableArray *rangeArray = [NSMutableArray array];
//    static NSRegularExpression *iExpression;
//    iExpression = iExpression ?: [NSRegularExpression regularExpressionWithPattern:@"@[^\s]+\s?" options:0 error:NULL];
//
//    [iExpression enumerateMatchesInString:traveAStr.string
//                                  options:0
//                                    range:NSMakeRange(0, traveAStr.string.length)
//                               usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
//                                   NSRange resultRange = result.range;
//                                   NSDictionary *attributedDict = [traveAStr attributesAtIndex:resultRange.location effectiveRange:&resultRange];
//                                   //                                   if ([attributedDict[NSForegroundColorAttributeName] isEqual:[UIColor redColor]]) {
////                                   for (ContactorModel * model in self.ngArr) {
////                                       if ([model.nickName isEqualToString:[traveAStr.string substringWithRange:result.range]]) {
////                                           [rangeArray addObject:NSStringFromRange(result.range)];
////                                       }
////                                   }
//
//                                   //                                   }
//                               }];
//    return rangeArray;
//
//}


- (void)photoBtnDidClickAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarPhotoBtnDidClickAction)]) {
        [self.delegate chatBarPhotoBtnDidClickAction];
    }
}

- (void)cameraBtnDidClickAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarCameraBtnDidClickAction)]) {
        [self.delegate chatBarCameraBtnDidClickAction];
    }
}
-(void)sendBusinessCardAction
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarBusinessCardDidClickAction)]) {
        [self.delegate chatBarBusinessCardDidClickAction];
    }
}

#pragma mark - setter

//- (void)setForbid:(BOOL)forbid {
//    _forbid = forbid;
//    self.forbidBtn.hidden = !forbid;
//}

#pragma mark - getter

- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.delegate = self;
//       _textView.placeholder = @"请输入消息内容";
        _textView.font = [UIFont systemFontOfSize:15];
        _textView.returnKeyType = UIReturnKeySend;
        _textView.backgroundColor = [UIColor clearColor];
        _textView.backgroundColor = KHEXCOLOR(kGrayColor_f2);
        [_textView configLayerWithBorderWidth:0 andWithCornerRadius:5 andWithBorderColor:[UIColor clearColor]];
        _textView.contentInset = UIEdgeInsetsMake(5, 0, 5, 0);
    }
    return _textView;
}

- (UIButton *)voiceBtn {
    if (!_voiceBtn) {
        _voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_voiceBtn setImage:[UIImage imageNamed:@"icon- 语音 (1)"] forState:UIControlStateNormal];
        [_voiceBtn setImage:[UIImage imageNamed:@"键盘"] forState:UIControlStateSelected];
        [_voiceBtn addTarget:self action:@selector(voiceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceBtn;
}

- (UIButton *)faceBtn {
    if (!_faceBtn) {
        _faceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_faceBtn setImage:[UIImage imageNamed:@"icon- 表情"] forState:UIControlStateNormal];
        [_faceBtn addTarget:self action:@selector(faceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _faceBtn;
}

- (UIButton *)moreBtn {
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreBtn setImage:[UIImage imageNamed:@"icon- 更多+"] forState:UIControlStateNormal];
        [_moreBtn addTarget:self action:@selector(moreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtn;
}
- (UIButton *)mentBtn {
    if (!_mentBtn) {
        _mentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_mentBtn setImage:[UIImage imageNamed:@"菜单"] forState:UIControlStateNormal];
        [_mentBtn setImage:[UIImage imageNamed:@"键盘"] forState:UIControlStateSelected];
        [_mentBtn addTarget:self action:@selector(mentBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _mentBtn;
}

//- (UIButton *)forbidBtn {
//    if (!_forbidBtn) {
//        _forbidBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        _forbidBtn.backgroundColor = [UIColor clearColor];
//        [_forbidBtn addTarget:self action:@selector(forbidBtnction:) forControlEvents:UIControlEventTouchUpInside];
//        _forbidBtn.hidden = YES;
//    }
//    return _forbidBtn;
//}

- (BTChatBarToolView *)toolView {
    if (!_toolView) {
        _toolView = [BTChatBarToolView loadFromNib];
        _toolView.delegate = self;
    }
    return _toolView;
}

- (BTStickerKeyboardView *)stickerView {
    if (!_stickerView) {
        _stickerView = [BTStickerKeyboardView loadFromNib];
        _stickerView.delegate = self;
    }
    return _stickerView;
}

- (UIButton *)voiceRecordBtn {
    if (!_voiceRecordBtn) {
        _voiceRecordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_voiceRecordBtn setTitle:@"按住说话" forState:UIControlStateNormal];
        [_voiceRecordBtn setTitle:@"松开结束" forState:UIControlStateHighlighted];
        [_voiceRecordBtn setTitleColor:KHEXCOLOR(kBlackColor) forState:UIControlStateNormal];
        [_voiceRecordBtn setTitleColor:KHEXCOLOR(kBlackColor) forState:UIControlStateHighlighted];
        _voiceRecordBtn.backgroundColor = [UIColor whiteColor];
        _voiceRecordBtn.backgroundColor = KHEXCOLOR(kGrayColor_f2);
        [_voiceRecordBtn configLayerWithBorderWidth:0 andWithCornerRadius:18 andWithBorderColor:[UIColor clearColor]];
        _voiceRecordBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        [_voiceRecordBtn addTarget:self action:@selector(recordButtonTouchBegin) forControlEvents:UIControlEventTouchDown];
        [_voiceRecordBtn addTarget:self action:@selector(recordButtonTouchEnd) forControlEvents:UIControlEventTouchUpInside];
        [_voiceRecordBtn addTarget:self action:@selector(recordButtonTouchUpOutside) forControlEvents:UIControlEventTouchUpOutside];
        [_voiceRecordBtn addTarget:self action:@selector(recordButtonTouchUpOutside) forControlEvents:UIControlEventTouchDragOutside];
        _voiceRecordBtn.hidden = YES;
    }
    return _voiceRecordBtn;
}

- (UIView *)menuView{
    if (!_menuView) {
        _menuView = [UIView new];
        _menuView.backgroundColor = [UIColor whiteColor];
//        _menuView.hidden = YES;
        for (int i=0; i<3; i++) {
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.backgroundColor = [UIColor clearColor];
            [btn setTitleColor:KHEXCOLOR(AllBackColor_titleColor) forState:UIControlStateNormal];
            btn.frame = CGRectMake((kScreenWidth-2)/3 * i, 10, (kScreenWidth-2)/3, 30);
            btn.tag = 1000+i;
            [btn addTarget:self action:@selector(mentBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [_menuView addSubview:btn];
            if (i!=2) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(btn.right, btn.top, 1, btn.height)];
                line.backgroundColor = kColor_Gray;
                [_menuView addSubview:line];
            }
            
        }
    }
    return _menuView;
}

- (void)recordButtonTouchBegin {
    // 开始录音
      NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    doucument = [doucument stringByAppendingPathComponent:kMessageVoiceFileName];
    NSString *recordPath = [doucument stringByAppendingFormat:@"/%.0f", [[NSDate date] timeIntervalSince1970] * 1000];
    WS(ws);
    [AudioRecordHelper shareAudioRecordHelper].delegate = self;
    [[AudioRecordHelper shareAudioRecordHelper] startRecordWithPath:recordPath completion:^(NSError * _Nonnull error) {
        if (error) {
            [ws recordButtonTouchUpOutside];
        } else {
            if (ws.delegate && [ws.delegate respondsToSelector:@selector(chatBarRecordAudioViewStartRecord)]) {
                [ws.delegate chatBarRecordAudioViewStartRecord];
            }
        }
    }];
}

- (void)recordButtonTouchEnd {
   // 录音结束
    WS(ws);
    [[AudioRecordHelper shareAudioRecordHelper] stopRecordWithCompletion:^(NSString * _Nonnull path, NSInteger timeLength) {
        if (ws.delegate && [ws.delegate respondsToSelector:@selector(chatBarRecordAudioViewStopRecord:timeLength:)]) {
            [ws.delegate chatBarRecordAudioViewStopRecord:path timeLength:timeLength];
        }
    }];
}

- (void)recordButtonTouchUpOutside {
    // 取消录音
    [[AudioRecordHelper shareAudioRecordHelper] cancelRecord];
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarRecordAudioViewCancelRecord)]) {
        [self.delegate chatBarRecordAudioViewCancelRecord];
    }

}

#pragma mark - AudioRecordHelperDelegate

- (void)audioRecordHelperRecordTimeout {
    self.voiceRecordBtn.selected = NO;
    // 录音结束
    WS(ws);
    [[AudioRecordHelper shareAudioRecordHelper] stopRecordWithCompletion:^(NSString * _Nonnull path, NSInteger timeLength) {
        if (ws.delegate && [ws.delegate respondsToSelector:@selector(chatBarRecordAudioViewStopRecord:timeLength:)]) {
            [ws.delegate chatBarRecordAudioViewStopRecord:path timeLength:timeLength];
        }
    }];
}
-(void)audioCountdownWithTime:(NSInteger)time
{
    if ([self.delegate respondsToSelector:@selector(chatCountdownAnimationWithTime:)]) {
        [self.delegate chatCountdownAnimationWithTime:time];
    }
    
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.voiceRecordBtn.jk_touchAreaInsets = UIEdgeInsetsMake(10, 0, 0, 10);
}
@end
